package com.ruike.alisurface.ui.payPage;

import android.os.Bundle;
import android.os.SystemClock;
import android.widget.TextView;

import com.ruike.alisurface.Constant;
import com.ruike.alisurface.R;
import com.ruike.alisurface.Serials.MsgEventBus;
import com.ruike.alisurface.Serials.ShopInfoUtils;
import com.ruike.alisurface.Serials.outGoods.ShengJiangJiUtils;
import com.ruike.alisurface.Serials.outGoods.ShopChUtils;
import com.ruike.alisurface.base.BaseAty;
import com.ruike.alisurface.bean.ShopDetailBean;
import com.ruike.alisurface.http.MchApiHttp;
import com.ruike.alisurface.project_DaTi.http.QuestionHttpTools;
import com.ruike.alisurface.ui.mainPage.MainActivity;
import com.voodoo.lib_utils.L;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;

import static com.ruike.alisurface.utils.ShareKey.Type_Chshopzl;
import static com.ruike.alisurface.utils.ShareKey.Type_Chshopzl_OLD;

/**
 * 支付出货页
 */
public class PayShowShopActivity extends BaseAty {

    @BindView(R.id.ali_card_count_time)
    TextView selectPayCountDownTv;

    ShopDetailBean paycarlist;
    double monery = 0.00;
    int outGoodsNumber = 0; // 升降机出货数量回调计数

    volatile int shopcount = 0;
    List<String> serialList = new ArrayList<>();
    Timer timer = new Timer();
    private String paytype;

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_rk_showshop;
    }

    @Override
    protected void initViews() {
        L.iTag("toshop", "支付出货页==" + this.getClass().getName());
    }

    @Override
    protected void initData() {

        paytype = getIntent().getExtras().getString("pay_type");

        paycarlist = (ShopDetailBean) getIntent().getSerializableExtra("orderrBeanData");
        if (paycarlist == null) {
            return;
        }
        for (int i = 0; i < paycarlist.getDetailOrderList().size(); i++) {
            monery += Double.valueOf(paycarlist.getDetailOrderList().get(i).getPrice());
            shopcount += paycarlist.getDetailOrderList().get(i).getQuantity();

        }
        L.iTag("toshop", "出货数量--" + shopcount);

        // 如果是升降机则注册升降机出货的结果回调和处理回调结果
        if (Constant.machineType == 2) {
            ShengJiangJiUtils.setOnSJJListener(new ShengJiangJiUtils.OnSJJOutGoodsListener() {
                @Override
                public void outGoodsSuccess() {
                    outGoodsNumber++;
                    if (outGoodsNumber >= paycarlist.getDetailOrderList().size()) {
                        todoPage(true);
                    }
                }

                @Override
                public void outGoodsFailure(String msg) {
                    outGoodsNumber++;
                    if (outGoodsNumber >= paycarlist.getDetailOrderList().size()) {
                        todoPage(false);
                    }
                }
            });
        } else {
            int time_shopcount = shopcount;
            if (time_shopcount > 0) {
                timer.schedule(new TimerTask() {
                    @Override
                    public void run() {
                        L.iTag("toshop", " 计时结束出货页面--");
                        todoPageAty();
                    }
                }, 8300 * time_shopcount);
            }
        }

        if (paycarlist.getDetailOrderList().size() > 0) {
            PutGoods();
        }
    }

    /**
     * 出货方法
     */
    private void PutGoods() {
        try {
            // 判断数据是否已经存在
            Thread thread = new Thread() {
                public void run() {
                    try {
                        for (int i = 0; i < paycarlist.getDetailOrderList().size(); i++) {
                            int type = paycarlist.getDetailOrderList().get(i).getSlotTypeId();
                            int index = paycarlist.getDetailOrderList().get(i).getSlotIndex();
                            int count = paycarlist.getDetailOrderList().get(i).getQuantity();
                            L.iTag("toshop", "tjf==" + "run: 出货货道："
                                    + index + "出货类型==" + type + "==出货数量=" + count);

                            if (Constant.machineType == 1) { // IC2出货
                                for (int j = 0; j < count; j++) {
                                    ShopChUtils.shopTodo(type, index);

                                }
                            } else if (Constant.machineType == 2) { // 升降机出货
                                ShengJiangJiUtils.outGoods(index, type);
                            }

                        }
                    } catch (Exception e) {

                        L.iTag("toshop", " Exception==" + e.getMessage());
                    }
                }
            };
            thread.start();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        Constant.showShop = true;
    }

    @Override
    protected void onResume() {
        super.onResume();
        startCountdownTimer(180, selectPayCountDownTv, MainActivity.class);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        L.iTag("toshop", "onDestroy 出货页销毁 ");
        Constant.showShop = false;
    }

    @Override
    public void onSuccess(String requestUrl, String requestJsonStr) {
        super.onSuccess(requestUrl, requestJsonStr);
        if (requestUrl.endsWith("confirm_question_order") || requestUrl.endsWith("Rk_Card_EndOrder") || requestUrl.endsWith("EndOrder")) {
            L.iTag("toshop", requestUrl + "===onSuccess === +出货完成");
            todoPage(true);
        }
    }

    @Override
    public void onError(String requestUrl, String errorMsg) {
        super.onError(requestUrl, errorMsg);
        if (requestUrl.endsWith("confirm_question_order") || requestUrl.endsWith("Rk_Card_EndOrder") || requestUrl.endsWith("EndOrder")) {
            L.iTag("toshop", requestUrl + "===onError === +出货失败=" + errorMsg);
            todoPage(false);
        }
    }

    public void todoPage(boolean isSuccess) {
        Bundle bundle = getIntent().getExtras();
        paytype = bundle.getString("pay_type", "wechat");
        bundle.putString("order_id", paycarlist.getOrderId());
        bundle.putDouble("order_money", paycarlist.getTotal_fee());
        bundle.putDouble("actual_money", paycarlist.getPay_fee());

        if (slotBeanList.size() > 0) {
            bundle.putBoolean("isSuccess", false);
            bundle.putSerializable("slotList", (Serializable) slotBeanList);
        } else {
            bundle.putBoolean("isSuccess", isSuccess);
        }

        if (paytype.equals("wechat")) {
            bundle.putDouble("discount", paycarlist.getPromotion_fee());
        } else if (paytype.equals("alface")) {
            bundle.putDouble("discount", paycarlist.getDiscount_fee());
        } else if (paytype.equals("weCard")) {

        }
        startActivity(PayfaceSuccessActivity.class, bundle);
        finish();
    }

    @Override
    public void doEventBusResult(MsgEventBus event) {
        if (event.getType().equals(Type_Chshopzl)) {
            L.iTag("toshop", "每一次的返回值");
            ShopChUtils.setPutflag(false);
            serialList.add(event.getMessage());

            return;
        }
        if (event.getType().equals(Type_Chshopzl_OLD)) {

            return;
        }
        if (event.getType().equals("出货倒计时完成") || event.getType().equals("出货倒计时未完成")) {
            --shopcount;
            L.iTag("toshop", " 出货数量递减======" + shopcount);
            todoPageAty();
            return;
        }
    }

    List<ShopInfoUtils.slotBean> slotBeanList = new ArrayList<>();

    public void todoPageAty() {
        L.iTag("toshop", " 计时  出货数量--", shopcount, "开始上传信息及跳转完成页");
        if (shopcount == 0) {
            if (timer != null) {
                timer.cancel();
                timer.purge();
                timer = null;
            }
            if (serialList.size() > 0) {
                for (int i = 0; i < serialList.size(); i++) {
                    ShopInfoUtils.analyzeSlot(serialList.get(i), i, serialList.size(), 0);
                }
                if (ShopInfoUtils.dllist.size() > 0) {
                    for (ShopInfoUtils.slotBean slotBean : ShopInfoUtils.dllist) {
                        if (slotBean.getZdcount() <= 0) {
                            slotBeanList.add(slotBean);
                        }
                    }
                }

                ShopInfoUtils.sendCheckoutnotify(paycarlist.getOrderId());
            }
            shopcount = -1;
            serialList.clear();
            SystemClock.sleep(100);
            HashMap<String, Object> map = new HashMap<>();
            map.put("IsEnd", true);
            map.put("Remark", "完成");

            map.put("OrderNo", paycarlist.getOrderId());
//            MchApiHttp.getOrderIsEnd(this, map);
            QuestionHttpTools.confirmQuestionRrder(paycarlist.getOrderId(), true, "出货完成", this);

        }
    }
}
